// pages/register/register.js
const app = getApp();

Page({
  data: {
    userType: "student",
    username: "",
    realName: "",
    password: "",
    confirmPassword: "",
    major: "",
    gradeIndex: 0,
    gradeOptions: ["2021级", "2022级", "2023级", "2024级"],
    className: "",
    department: "",
    departmentOptions: ["书院", "学院", "学校"],
    departmentIndex: 0,
    position: "",
    loading: false,
    canRegister: false,
  },

  onLoad() {
    // 检查是否已登录
    if (app.globalData.userInfo) {
      this.redirectToHome();
    }
  },

  selectUserType(e) {
    const userType = e.currentTarget.dataset.type;
    this.setData({ userType });
    this.checkCanRegister();
  },

  onUsernameInput(e) {
    this.setData({ username: e.detail.value });
    this.checkCanRegister();
  },

  onRealNameInput(e) {
    this.setData({ realName: e.detail.value });
    this.checkCanRegister();
  },

  onPasswordInput(e) {
    this.setData({ password: e.detail.value });
    this.checkCanRegister();
  },

  onConfirmPasswordInput(e) {
    this.setData({ confirmPassword: e.detail.value });
    this.checkCanRegister();
  },

  onMajorInput(e) {
    this.setData({ major: e.detail.value });
    this.checkCanRegister();
  },

  onGradeChange(e) {
    this.setData({ gradeIndex: parseInt(e.detail.value) });
    this.checkCanRegister();
  },

  onClassNameInput(e) {
    this.setData({ className: e.detail.value });
    this.checkCanRegister();
  },

  onDepartmentChange(e) {
    const idx = parseInt(e.detail.value);
    this.setData({
      departmentIndex: idx,
      department: this.data.departmentOptions[idx],
    });
    this.checkCanRegister();
  },

  onPositionInput(e) {
    this.setData({ position: e.detail.value });
    this.checkCanRegister();
  },

  checkCanRegister() {
    const { userType, username, realName, password, confirmPassword } =
      this.data;

    let canRegister =
      username.trim() &&
      realName.trim() &&
      password.trim() &&
      confirmPassword.trim();

    // 检查密码长度
    if (password.length < 6 || password.length > 20) {
      canRegister = false;
    }

    // 检查密码确认
    if (password !== confirmPassword) {
      canRegister = false;
    }

    // 学生特有字段检查
    if (userType === "student") {
      const { major, className } = this.data;
      canRegister = canRegister && major.trim() && className.trim();
    }

    // 评委特有字段检查
    if (userType === "judge") {
      const { department, position } = this.data;
      canRegister = canRegister && department.trim() && position.trim();
    }

    this.setData({ canRegister });
  },

  async register() {
    if (!this.data.canRegister || this.data.loading) return;

    // 验证密码
    if (this.data.password !== this.data.confirmPassword) {
      wx.showToast({
        title: "两次密码输入不一致",
        icon: "error",
      });
      return;
    }

    if (this.data.password.length < 6 || this.data.password.length > 20) {
      wx.showToast({
        title: "密码长度应为6-20位",
        icon: "error",
      });
      return;
    }

    this.setData({ loading: true });

    try {
      const registerData = this.prepareRegisterData();
      const local = require("../../utils/local");
      const result = local.registerUser(registerData);

      if (result.success) {
        // 自动登录新注册用户，确保会话与当前学生一致
        wx.setStorageSync(
          "userInfo",
          registerData.userType === "student"
            ? {
                id: registerData.username,
                username: registerData.username,
                userType: registerData.userType,
                profile: {
                  major: registerData.major,
                  grade: registerData.grade,
                  className: registerData.className,
                },
                realName: registerData.realName,
              }
            : {
                id: registerData.username,
                username: registerData.username,
                userType: registerData.userType,
                profile: {
                  department: registerData.department,
                  position: registerData.position,
                },
                realName: registerData.realName,
                department: registerData.department,
              }
        );
        wx.setStorageSync("userType", registerData.userType);
        wx.showToast({
          title: "注册成功",
          icon: "success",
        });

        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: result.message || "注册失败",
          icon: "error",
        });
      }
    } catch (error) {
      console.error("注册错误:", error);
      wx.showToast({
        title: "本地注册异常",
        icon: "error",
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  prepareRegisterData() {
    const { userType, username, realName, password, gradeOptions, gradeIndex } =
      this.data;

    const baseData = {
      userType,
      username: username.trim(),
      realName: realName.trim(),
      password: password.trim(),
    };

    if (userType === "student") {
      return {
        ...baseData,
        major: this.data.major.trim(),
        grade: gradeOptions[gradeIndex],
        className: this.data.className.trim(),
      };
    } else {
      return {
        ...baseData,
        department: (
          this.data.department ||
          this.data.departmentOptions[this.data.departmentIndex]
        ).trim(),
        position: this.data.position.trim(),
      };
    }
  },

  // 删除远程注册请求，改为本地存储

  redirectToHome() {
    const { userType } = this.data;

    if (userType === "student") {
      wx.switchTab({
        url: "/pages/student/profile/profile",
      });
    } else {
      wx.navigateTo({
        url: "/pages/judge/dashboard/dashboard",
      });
    }
  },

  goToLogin() {
    wx.navigateBack();
  },
});
